package com.xuyiwei.mayi;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xuyiwei on 2019/4/17.
 */
public class ReferFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化...");
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("doFilter....");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //获取请求头中来源
        String referer = req.getHeader("referer");
        //获取当前请求名
        String serverName = request.getServerName();
        System.out.println("referer:"+referer+"----serverName:"+serverName+":"+serverName);
        if(referer==null||(!referer.contains(serverName))){
            req.getRequestDispatcher("/servletdemo2/imgs/error.jpeg").forward(req, res);
            return ;
        }
        chain.doFilter(req, res);
    }

    public void destroy() {

    }


}
